<template>
  <a-row :gutter="10">
    <a-col :md="leftColMd" :sm="24">
      <a-card :bordered="false">
        <!-- 查询区域 -->
        <search ref="search" :config="searchConfig" @search="search" @getHeight="getHeight"/>
        <div class="page_table">
          <vxe-grid
            ref="xGrid"
            :border="true"
            :resizable="true"
            :showOverflow="true"
            size="mini"
            :loading="loading"
            :height="pageHeight-seachHeight-90"
            :align="left"
            :columns="columns"
            :data="dataSource"
            :toolbar-config="tableToolbar"
            @radio-change="radioChangeEvent"
            :radio-config="{ trigger: 'row'}"
          >
            <template #toolbar_buttons>
              <div class="table-operator">
                <a-button @click="handleAdd" type="primary" v-has="'roleUserList:add'">新增</a-button>
                <a-button v-has="'roleUserList:delete'" @click="batchDel">删除</a-button>
                <a-button v-has="'roleUserList:export'" @click="downExportXls('cnProduct_service' )">导出</a-button>
              </div>
            </template>
            <template #detail="{row}">
              <a @click="handleDetail(row)">{{ row.roleCode }}</a>
            </template>
            <template #action="{ row:record }">
              <a v-has="'roleUserList:update'" @click="handleEdit(record)">编辑</a>
              <a-divider type="vertical"/>
              <a-dropdown>
                <a class="ant-dropdown-link">
                  更多
                  <a-icon type="down"/>
                </a>
                <a-menu slot="overlay">
                  <a-menu-item>
                    <a @click="handlePerssion(record.roleCode)">授权</a>
                  </a-menu-item>
                  <a-menu-item>
                    <a @click="handleOpen(record)">用户</a>
                  </a-menu-item>
                  <a-menu-item v-has="'business:log'">
                    <a href="javascript:;" @click='handleBusiness("角色管理",record)'>日志</a>
                  </a-menu-item>
                </a-menu>
              </a-dropdown>
            </template>

            <template #pager>
              <vxe-pager
                :layouts="['Total', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump','Sizes', 'FullJump']"
                :currentPage.sync="ipagination.current"
                :page-size.sync="ipagination.pageSize"
                :total="ipagination.total"
                :pageSizes="ipagination.pageSizeOptions"
                @page-change="handlePageChange">
              </vxe-pager>
            </template>
          </vxe-grid>
        </div>
        <!-- 右侧的角色权限配置 -->
        <user-role-modal ref="modalUserRole"></user-role-modal>
        <role-modal ref="modalForm" @ok="modalFormOk"></role-modal>
        <business-log ref="businessLog"></business-log>
      </a-card>
    </a-col>

    <a-col :md="rightColMd" :sm="24" v-if="this.rightcolval == 1">
      <a-card :bordered="false">
        <div style="text-align: right;position: absolute;top: 10px;right: 20px;z-index:9999 ">
          <a-icon type="close-circle" @click="hideUserList"/>
        </div>
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
          <a-form layout="inline">
            <a-row :gutter="24">
              <a-col :md="12" :sm="12">
                <a-form-item label="">
                  <a-input placeholder="用户账号" v-model="queryParam2.userName" style="width: 200px"></a-input>
                </a-form-item>
              </a-col>
              <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
            <a-col :md="9" :sm="24">
             <a-button type="primary" @click="searchQuery2" icon="search" style="margin-left: 21px">查询</a-button>
              <a-button type="primary" @click="searchReset2" icon="reload" style="margin-left: 8px">重置</a-button>
            </a-col>
          </span>
            </a-row>
          </a-form>
        </div>
        <div class="page_table">
          <vxe-grid
            ref="xGrid"
            :border="true"
            :resizable="true"
            :showOverflow="true"
            size="mini"
            :loading="loading"
            :height="pageHeight-seachHeight-90"
            :align="left"
            :columns="columns2"
            :data="dataSource2"
            :toolbar-config="tableToolbar"
            :checkbox-config="checkboxConfig"
            v-bind="vexConfig"
            @checkbox-change="selectChangeEvent"
            @checkbox-all="selectChangeEvent"
          >
            <template #toolbar_buttons>
              <div class="table-operator">
                <a-button @click="handleAdd2" type="primary">新增用户</a-button>
                <!--<a-button @click="handleEdit2" type="primary" icon="edit" style="margin-top: 16px">用户编辑</a-button>-->
                <a-button @click="handleAddUserRole" type="primary">已有用户</a-button>
                <a-dropdown v-if="selectedRowKeys2.length > 0">
                  <a-menu slot="overlay">
                    <a-menu-item key="1" @click="batchDel2">
                      <a-icon type="delete"/>
                      删除
                    </a-menu-item>
                  </a-menu>
                  <a-button style="margin-left: 8px"> 批量操作
                    <a-icon type="down"/>
                  </a-button>
                </a-dropdown>
              </div>
            </template>

            <template #status="{row}">
              {{ row.status == 1 ? '启用' : '停用' }}
            </template>

            <template #action="{ row:record }">
              <a @click="handleEdit2(record)">编辑</a>
              <a-divider type="vertical"/>
              <a-dropdown>
                <a class="ant-dropdown-link">
                  更多
                  <a-icon type="down"/>
                </a>
                <a-menu slot="overlay">
                  <a-menu-item>
                    <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete2(record.id)">
                      <a>删除</a>
                    </a-popconfirm>
                  </a-menu-item>
                </a-menu>
              </a-dropdown>
            </template>

            <template #pager>
              <vxe-pager
                :layouts="['Total', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump','Sizes', 'FullJump']"
                :currentPage.sync="ipagination2.current"
                :page-size.sync="ipagination2.pageSize"
                :total="ipagination2.total"
                :pageSizes="ipagination2.pageSizeOptions"
                @page-change="handlePageChange2">
              </vxe-pager>
            </template>
          </vxe-grid>
        </div>
        <!-- 表单区域 -->
        <user-modal ref="modalForm2" @ok="modalFormOk2"></user-modal>
        <SelectUserModal ref="selectUserModal" @selectFinished="selectOK"></SelectUserModal>
      </a-card>
    </a-col>
    <business-log ref="businessLog"></business-log>
  </a-row>
</template>
<script>
import { PageListMixin } from '@/mixins/PageListMixin'
import { deleteAction, postAction, getAction } from '@/api/manage'
import SelectUserModal from '@page-modules/SelectUserModal'
import RoleModal from '@page-modules/RoleModal'
import UserModal from '@page-modules/UserModal'
import { filterObj } from '@/utils/util'
import UserRoleModal from '@page-modules/UserRoleModal'
import moment from 'moment'

export default {
  name: 'RoleUserList',
  mixins: [PageListMixin],
  components: {
    UserRoleModal,
    SelectUserModal,
    RoleModal,
    UserModal,
    moment,
  },
  data() {
    return {
      model1: {},
      model2: {},
      currentRoleId: '',
      queryParam1: {},
      queryParam2: {},
      dataSource1: [],
      dataSource2: [],
      ipagination1: {
        current: 1,
        size: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },

      ipagination2: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: [10, 20, 30, 40, 50],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      isorter1: {
        column: 'createTime',
        order: 'desc'
      },
      isorter2: {
        column: 'createTime',
        order: 'desc'
      },
      filters1: {},
      filters2: {},
      loading1: false,
      loading2: false,
      selectedRowKeys1: [],
      selectedRowKeys2: [],
      selectionRows1: [],
      selectionRows2: [],
      test: {},
      rightcolval: 0,
      columns: [
        { type: 'radio', width: 50, fixed: 'left' },

        {
          fixed: 'left',
          title: '角色编号',
          minWidth: 100,
          field: 'roleCode',
          slots: { default: 'detail' }
        },
        {
          title: '角色名称',
          minWidth: 100,
          field: 'roleName'
        },
        {
          title: '创建人',
          align: 'left',
          minWidth: 80,
          field: 'createName'
        },
        {
          title: '创建时间',
          align: 'left',
          minWidth: 80,
          field: 'createTime'
        },
        {
          title: '更新人',
          align: 'left',
          minWidth: 80,
          field: 'updateName'
        },
        {
          title: '更新时间',
          align: 'left',
          minWidth: 80,
          field: 'updateTime'
        },
        {
          title: '操作',
          field: 'action',
          minWidth: 100,
          slots: { default: 'action' }
        }
      ],

      columns2: [
        { type: 'checkbox', width: 50, fixed: 'left' },
        {
          title: '用户账号',
          field: 'userName',
          minWidth: 100
        }, {
          title: '用户名称',
          minWidth: 100,
          field: 'realName'
        }, {
          title: '状态',
          minWidth: 100,
          field: 'status',
          slots: { default: 'status' }
        }, , {
          title: '操作',
          field: 'action',
          slots: { default: 'action' },
          minWidth: 120
        }],
      searchConfig: [
        {
          type: 'input',
          name: 'roleCode',
          placeholder: '角色编号'
        },
        {
          type: 'input',
          name: 'roleName',
          placeholder: '角色名称'
        }
      ],
      // 高级查询参数
      superQueryParams2: '',
      // 高级查询拼接条件
      superQueryMatchType2: 'and',
      url: {
        list: window._CONFIG['domianURL'] + '/cnRoleController/getRoleList',
        delete: window._CONFIG['domianURL'] + '/cnRoleController/deleteByid',
        list2: window._CONFIG['domianURL'] + '/cnUserRoleController/findUserRoleList',
        addUserRole: window._CONFIG['domianURL'] + '/cnRoleController/addSysUserRole',
        delete2: window._CONFIG['domianURL'] + '/cnUserRoleController/deleteUserRole',
        deleteBatch2: window._CONFIG['domianURL'] + '/sys/user/deleteUserRoleBatch',
        deleteBatch:  "/cnRoleController/deleteBatch",
        exportXlsUrl: window._CONFIG['domianURL'] + 'sys/role/exportXls',
        importExcelUrl: window._CONFIG['domianURL'] + 'sys/role/importExcel'
      }
    }
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },

    leftColMd() {
      return this.rightcolval == 0 ? 24 : 12
    },
    rightColMd() {
      return this.rightcolval == 0 ? 0 : 12
    }
  },
  methods: {
    onSelectChange2(selectedRowKeys, selectionRows) {
      this.selectedRowKeys2 = selectedRowKeys
      this.selectionRows2 = selectionRows
    },
    onClearSelected2() {
      this.selectedRowKeys2 = []
      this.selectionRows2 = []
    },
    // vxe表格多选
    selectChangeEvent() {
      const $grid = this.$refs.xGrid
      this.selectionRows2 = $grid.getCheckboxRecords()
      this.selectedRowKeys2 = this.selectionRows.map(item => item[this.tableKey])
    },
    // vxe表格单选
    radioChangeEvent({ row }) {
      // this.rightcolval = 1
      this.selectionRows1 = [row]
      this.selectedRowKeys1 = [row[this.tableKey]]
      this.selectionRows = [row]
      this.selectedRowKeys = [row[this.tableKey]]
      this.currentRoleId = row[this.tableKey]
      this.model1 = Object.assign({}, row)
      this.onClearSelected2()
      this.loadData2()
    },
    onClearSelected() {
    },

    getQueryParams2() {
      //获取查询条件
      let sqp = {}
      if (this.superQueryParams2) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams2)
        sqp['superQueryMatchType'] = this.superQueryMatchType2
      }
      var param = Object.assign(sqp, this.queryParam2, this.isorter2, this.filters2)
      param.field = this.getQueryField2()
      param.current = this.ipagination2.current
      param.size = this.ipagination2.pageSize
      return filterObj(param)
    },
    getQueryField2() {
      //TODO 字段权限控制
      var str = 'id,'
      this.columns2.forEach(function (value) {
        str += ',' + value.field
      })
      return str
    },
    handleEdit2: function (record) {
      this.$refs.modalForm2.title = '编辑'
      this.$refs.modalForm2.roleDisabled = true
      this.$refs.modalForm2.edit(record)
    },
    handleDetail2: function (record) {
      this.$refs.modalForm2.title = '详情'
      this.$refs.modalForm2.roleDisabled = false
      this.$refs.modalForm2.edit(record)
    },
    handleAdd2: function () {
      if (this.currentRoleId == '') {
        this.$message.error('请选择一个角色!')
      } else {
        this.$refs.modalForm2.roleDisabled = true
        this.$refs.modalForm2.selectedRole = [this.currentRoleId]

        this.$refs.modalForm2.add()

        this.$refs.modalForm2.title = '新增'
      }
    },
    modalFormOk2() {
      // 新增/修改 成功时，重载列表
      this.loadData2()
    },
    loadData2(arg) {
      if (!this.url.list2) {
        this.$message.error('请设置url.list2属性!')
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination2.current = 1
      }
      if (this.currentRoleId === '') return
      let params = this.getQueryParams2()//查询条件
      params.roleCode = this.dataSource.find(item => item.id == this.currentRoleId).roleCode
      this.loading2 = true
      var that = this
      postAction(this.url.list2, params).then((res) => {
        if (res.success) {
          that.dataSource2 = res.result.records
          that.ipagination2.total = res.result.total

        }
        that.loading2 = false
      })

    },
    handleDelete1: function (id) {
      this.handleDelete(id)
      this.dataSource2 = []
      this.currentRoleId = ''
    },
    handleDelete2: function (id) {
      if (!this.url.delete2) {
        this.$message.error('请设置url.delete2属性!')
        return
      }
      var that = this
      getAction(that.url.delete2, { roleId: this.currentRoleId, userId: id }).then((res) => {
        if (res.success) {
          that.$message.success(res.message)
          that.loadData2()
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    batchDel2: function () {

      if (!this.url.deleteBatch2) {
        this.$message.error('请设置url.deleteBatch2属性!')
        return
      }
      if (this.selectedRowKeys2.length <= 0) {
        this.$message.warning('请选择一条记录！')
        return
      } else {
        var ids = ''
        for (var a = 0; a < this.selectedRowKeys2.length; a++) {
          ids += this.selectedRowKeys2[a] + ','
        }
        var that = this
        console.log(this.currentDeptId)
        this.$confirm({
          title: '确认删除',
          content: '是否删除选中数据?',
          onOk: function () {
            deleteAction(that.url.deleteBatch2, { roleId: that.currentRoleId, userIds: ids }).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.loadData2()
                that.onClearSelected()
              } else {
                that.$message.warning(res.message)
              }
            })
          }
        })
      }
    },
    selectOK(data) {
      let params = {}
      params.roleCode = this.currentRoleId
      params.items = []
      for (var a = 0; a < data.length; a++) {
        params.items.push(data[a].userName)
      }
      postAction(this.url.addUserRole, params).then((res) => {
        if (res.success) {
          this.loadData2()
          this.$message.success(res.message)
        } else {
          this.$message.warning(res.message)
        }
      })
    },

    handleAddUserRole() {
      if (this.currentRoleId == '') {
        this.$message.error('请选择一个角色!')
      } else {
        this.$refs.selectUserModal.isfilterRole = 1
        this.$refs.selectUserModal.visible = true
        this.$refs.selectUserModal.roleCode = this.dataSource.find(item => item.id == this.currentRoleId).roleCode
      }
    },
    handleOpen(record) {
      this.rightcolval = 1
      this.selectedRowKeys1 = [record.id]
      this.model1 = Object.assign({}, record)
      this.currentRoleId = record.id
      this.onClearSelected2()
      this.loadData2()
    },
    /*handleEdit: function(record) {
      if (this.currentRoleId == '') {
        this.$message.error('请选择一个角色!')
      } else {
        this.$refs.modalForm.edit(record)
        this.$refs.modalForm.title = '编辑'
      }
    },*/
    searchQuery2() {
      this.loadData2(1)
    },
    searchReset2() {
      this.queryParam2 = {}
      this.loadData2(1)
    },
    // // vxe表格分页
    // handlePageChange({ currentPage, pageSize }) {
    //   this.ipagination2.currentPage = currentPage
    //   this.ipagination2.pageSize = pageSize
    //   this.loadData2()
    // },
    // vxe表格分页
    handlePageChange2({ currentPage, pageSize }) {
      this.ipagination2.currentPage = currentPage
      this.ipagination2.pageSize = pageSize
      this.loadData2()
    },

    hideUserList() {
      this.rightcolval = 0
      // this.selectedRowKeys1 = []
    },
    handlePerssion(roleId) {
      this.$refs.modalUserRole.show(roleId)
    }
  }
}
</script>
<style scoped>
/** Button按钮间距 */

</style>
